package com.atguigu.gulimall.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
public class MyHeaderFooter extends PdfPageEventHelper {
	private static PdfTemplate total;

	private static BaseFont bfChinese;

	private static BaseFont bfEnglish;

	private static String bfmonth;

	private static String logoFilePath;

	private static Integer size;//页脚字体大小

	public MyHeaderFooter(PdfTemplate total, BaseFont bfChinese, BaseFont bfEnglish, String bfmonth) {
		MyHeaderFooter.total = total;
		MyHeaderFooter.bfChinese = bfChinese;
		MyHeaderFooter.bfEnglish = bfEnglish;
		MyHeaderFooter.bfmonth = bfmonth;
	}

	public MyHeaderFooter(BaseFont bfChinese, BaseFont bfEnglish, String bfmonth, String logoFilePath) {
		MyHeaderFooter.bfChinese = bfChinese;
		MyHeaderFooter.bfEnglish = bfEnglish;
		MyHeaderFooter.bfmonth = bfmonth;
		MyHeaderFooter.logoFilePath = logoFilePath;
	}

	public MyHeaderFooter(BaseFont bfChinese, BaseFont bfEnglish, String bfmonth, Integer size) {
		MyHeaderFooter.bfChinese = bfChinese;
		MyHeaderFooter.bfEnglish = bfEnglish;
		MyHeaderFooter.bfmonth = bfmonth;
		MyHeaderFooter.size = size;
	}

	/**
	 * 重写PdfPageEventHelper中的onOpenDocument方法
	 */
	@Override
	public void onOpenDocument(PdfWriter writer, Document document) {
		// 得到文档的内容并为该内容新建一个模板
		total = writer.getDirectContent().createTemplate(560, 30);
		try {
			// 设置字体对象为Windows系统默认的字体
			//bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		} catch (Exception e) {
			throw new ExceptionConverter(e);
		}
	}

	/**
	 * 重写PdfPageEventHelper中的onEndPage方法
	 */
	@SneakyThrows
	@Override
	public void onEndPage(PdfWriter writer, Document document) {

//		Image image = Image.getInstance("E:\\JavaProject\\00_resourcecode\\trunk\\sidp_oracle\\src\\main\\resources\\images\\logo.png");
//		Font headFont = PdfTemplateUtils.english_arial_normal_10f;
//
//		PdfPTable table = PDFTemplateUtils.createTable(new float[]{210, 270});

//		Phrase phraseTitle = new Phrase();
//		PdfTemplate template = PdfTemplate.createTemplate(writer, document.getPageSize().getWidth(), document.getPageSize().getHeight());
//		ImgTemplate imgTemplate = new ImgTemplate(template);
//		image.makeMask();
//		imgTemplate.setImageMask(image);
//		phraseTitle.add(imgTemplate);
//		StringBuffer underline = new StringBuffer();
//		for(int i = 0;i<116;i++) {
//			underline.append("_");
//		}
//		Phrase contentPh = new Phrase("这是是页眉",headFont);
//		Phrase underlinePh = new Phrase(underline.toString(),headFont);
//		Phrase pageNumberPh = new Phrase(String.valueOf(document.getPageNumber()),headFont);


//		float center = document.getPageSize().getRight()/2;//页面的水平中点
//		float top = document.getPageSize().getTop()-36;
//		float bottom = document.getPageSize().getBottom()+36;

//		Phrase im = new Phrase(new Chunk(image, center, top - 6, true));


		/** 参数xy是指文本显示的页面上的哪个點。alignment指文本在坐标点的对齐方式 */
//		ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,contentPh,center,top,0); //页眉
//		ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER,underlinePh,center,top-6,2); //页眉
//		ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER,pageNumberPh,center,bottom,0); //页码







		// 新建获得用户页面文本和图片内容位置的对象
		PdfContentByte pdfContentByte = writer.getDirectContent();
		// 保存图形状态
		pdfContentByte.saveState();
		setImg(writer, logoFilePath, 170, 90, 10, 785);
		String text = "Page " + writer.getPageNumber() + " of ";
		// 获取点字符串的宽度
		float textSize = bfChinese.getWidthPoint(text, 6);
		if (size!=null){
			textSize = bfChinese.getWidthPoint(text, size);
		}
		pdfContentByte.beginText();
		// 设置随后的文本内容写作的字体和字号
		if (size!=null){
			pdfContentByte.setFontAndSize(bfChinese, size);
		}else {
			pdfContentByte.setFontAndSize(bfChinese, 6);
		}
		// 定位'X/'
		float x = (document.right() + document.left()) / 2-10;
		float y = 20f;
		pdfContentByte.setTextMatrix(x, y);
		pdfContentByte.showText(text);
		pdfContentByte.setTextMatrix(30, y);
//		pdfContentByte.showText("立橋人壽保險有限公司 "); // 頁尾文字
		// 设置随后的文本内容写作的字体和字号
		if (size!=null) {
			pdfContentByte.setFontAndSize(bfEnglish, size);
		} else {
			pdfContentByte.setFontAndSize(bfEnglish, 6);
		}
		pdfContentByte.endText();
		// 将模板加入到内容（content）中- // 定位'Y'
		pdfContentByte.addTemplate(total, x + textSize, y);
		pdfContentByte.restoreState();
	}

	/**
	 * 重写PdfPageEventHelper中的onCloseDocument方法
	 */
	@Override
	public void onCloseDocument(PdfWriter writer, Document document) {
		total.beginText();
		if (size!=null){
			total.setFontAndSize(bfChinese, size);
		}else {
			total.setFontAndSize(bfChinese, 6);
		}
		total.setTextMatrix(0, 0);
		// 设置总页数的值到模板上，并应用到每个界面
		total.showText(String.valueOf(writer.getPageNumber()));
		try {
			//bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			if (size!=null){
				total.setFontAndSize(bfEnglish, size);
			}else {
				total.setFontAndSize(bfEnglish, 6);
			}
		} catch (Exception e) {
			log.error("error", e);
		}
		if (size!=null){
			total.setTextMatrix(120, 0);
		}else {
			total.setTextMatrix(140, 2);
		}
		total.endText();
	}


	public static void setImg(PdfWriter writer, String path, float fitWidth, float fitHeight, float absoluteX, float absoluteY) {
		try {
			Image image = getImageFromInputStream(Objects.requireNonNull(MyHeaderFooter.class.getClassLoader().getResourceAsStream("images/logo.png")));
			image.setAlignment(Image.MIDDLE);
			image.scaleToFit(fitWidth, fitHeight);
			image.setAbsolutePosition(absoluteX, absoluteY);
			writer.getDirectContent().addImage(image);
		} catch (Exception e) {
			log.error("error", e);
			log.error("[ERROR] Set Img : img file does not exist.");
		}
	}

	/**
	 *
	 * @param inputStream
	 * @return 将InputStream转化为Image
	 * @throws Exception
	 */
	public static Image getImageFromInputStream(InputStream inputStream) throws Exception {
		int n;
		byte[] buffer = new byte[4096];
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		while (-1 != (n = inputStream.read(buffer))) {
			output.write(buffer, 0, n);
		}
		Image image = Image.getInstance(output.toByteArray());
		return image;
	}
}
